//MyFirstPlugin
//SeperatedBackpack.js

var path="./plugins/BlocklyNukkit/SeperatedBackpack/";

function PluginEnableEvent(evt)
{
    if(manager.readFile(path+"config.yml")==="FILE NOT FOUND")
    {
        logger.warning("配置文件不存在，重新建立！");
        manager.createConfig(manager.getFile("SeperatedBackpack", "config.yml"),2);
    }
    logger.info("SeperatedBackpack已成功加载！");
}

function refresh(bgn,edn,player)
{
    //保存物品栏
    let pinv=inventory.getPlayerInv(player);
    let items=inventory.getItemsInInv(pinv);
    let ninv=inventory.addInv(false,Java.to([],'cn.nukkit.item.Item[]'),"");
    let bjson=[];
    for (let i=0;i<items.length;i++)
        bjson[i]={"id":items[i].getId(),"data":items[i].getDamage(),"count":items[i].getCount(),"nbt":blockitem.getNBTString(items[i])};
    manager.writeFile(path+player.getName()+bgn+".json",JSON.stringify(bjson));
    inventory.setPlayerInv(player,ninv);
    
    //载入物品栏
    let text=manager.readFile(path+player.getName()+edn+".json");
    if(text!=="FILE NOT FOUND")
    {
        bjson = JSON.parse(text);
        items = [];
        for(let i=0;i<bjson.length;i++){
            let item=blockitem.buildItem(bjson[i].id,bjson[i].data,bjson[i].count);
            if(bjson[i].nbt!==null)
               blockitem.putinNBTString(item,bjson[i].nbt); 
            items.push(item);
        }
        let inv=inventory.addInv(true,Java.to(items,'cn.nukkit.item.Item[]'),'');
        inventory.setPlayerInv(player,inv);
    }
}

function PlayerGameModeChangeEvent(evt)
{
    let player=evt.getPlayer();
    if(evt.getNewGamemode()===1)
    {
        refresh("0","1",player);
        player.sendMessage("你已由生存模式转为创造模式，生存物品将为你暂时保管！");
    }
    else if(evt.getNewGamemode()===0)
    {
        refresh("1","0",player);
        player.sendMessage("你已由创造模式转为生存模式，创造物品将为你暂时保留！");
    }
}